package com.atguigu.ds.demo;

import com.atguigu.ds.List;
import com.atguigu.ds.Map;

import java.util.function.Consumer;

public class MyArray<E> implements List<E> {

    //数组容量
    private static final int DEFAULT_CAPACITY = 3;

    //new Object[INITIAL_CAPACITY]
    //private  E[] EMPTY_ELEMENTDATA = new E[DEFAULT_CAPACITY];

    //数组
    private Object[] array = {};

    //构造器:初始化数组
    public MyArray() {
        //泛型擦除
        //new E[3];
        this.array = new Object[DEFAULT_CAPACITY];
    }
    private int size;
    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }

    //添加尾部元素
    @Override
    public void add(E element) {
        add(size,element);
    }

    //按索引位置添加元素
    @Override
    public void add(int index, E element) {
        if (index >size || index <0){
            throw new IndexOutOfBoundsException(index);
        }

        if (size >= array.length){
            grow();
        }
        //添加元素移动
        for (int i = size-1; i >= index; i--) {
            array[i+1]=array[i];
        }
        //添加
        array[index] = element;

        size++;
    }

    private void grow() {
        //获取原始数组长度
        int currentLength = array.length;
        //创建新数组，原始长度*2
        Object[] newArray = new Object[currentLength*2];

        //把原始的数据放到新数组里面
        for (int i = 0; i < size; i++) {
            newArray[i] = array[i];
        }

        array = newArray;
    }
    //获取下标
    @Override
    public E get(int index) {
        if (index >= size || index<0){
            throw  new IndexOutOfBoundsException(index);
        }
        return (E) array[index];
    }
    //按下标删除
    @Override
    public E remove(int index) {
        return null;
    }
    //添加
    @Override
    public E set(int index, E element) {
        if (index >= 0 || index <0){
            throw new IndexOutOfBoundsException(index);
        }
        E oldValue = (E) array[index];
        array[index] = element;
        return oldValue;
    }

    @Override
    public void forEach(Consumer<E> consumer) {
        for (int i = 0; i < size; i++) {
            consumer.accept((E) array[i]);
        }

    }

/*
* 数组内容展示形式为[1,2,3,4,5,6]
* */
    public String toString(){
        if (size == 0)
            return "[]";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append('[');
        for (int i = 0; i < size; i++) {
            stringBuilder.append((E) array[i]).append(',');
        }
        stringBuilder.replace(stringBuilder.length() -1,stringBuilder.length(),"]");


        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        MyArray<Integer> MyArray = new MyArray<>();
        MyArray.add(0,1);
        MyArray.add(1,11);
        MyArray.add(2,111);
        MyArray.add(3,1111);

        System.out.println(MyArray);
    }
}





















